package com.example.captcha_demo.Controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captcha_demo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("captcha")
public class CaptchaController {

    //验证码超时时间:10min
    private static final long CAPTCHA_TIME_OUT=10*60*1000;

    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("getCaptcha")
    public void createCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        LineCaptcha lineCaptcha= CaptchaUtil.createLineCaptcha(200,100);//创建一个验证码
        String code=lineCaptcha.getCode();//获取验证码
        System.out.println(captchaProperties.getWidth1());
        System.out.println("验证码是:"+code);
        session.setAttribute("CAPTCHA_CODE",code);//设置session
        session.setAttribute("CAPTCHA_TIME",System.currentTimeMillis());

        response.setContentType("image/png");//设置contentType
        lineCaptcha.write(response.getOutputStream());//写入到输出流
        response.getOutputStream().close();
    }

    @RequestMapping("/check")
    public boolean check(String captcha,HttpSession session){
        //用户传入参数校验
        if(!StringUtils.hasLength(captcha)){
            return false;
        }

        //获取session中参数
        String captcha_code =(String) session.getAttribute("CAPTCHA_CODE");
        Long captcha_time = (Long) session.getAttribute("CAPTCHA_TIME");

        //参数及超时校验
        if(!StringUtils.hasLength(captcha_code)||captcha_time==null
                || (System.currentTimeMillis()-captcha_time>CAPTCHA_TIME_OUT)){
            return false;
        }

        //不区分大小写
        if(captcha.equalsIgnoreCase(captcha_code)){
            return true;
        }
        return false;
    }

}
